package org.wattdepot.cli.commands;

import javax.xml.datatype.XMLGregorianCalendar;
import org.wattdepot.cli.UserCommandInterface;
import org.wattdepot.client.WattDepotClientException;

/**
 * Contains methods that list the power at a given timestamp.
 * 
 * @author Jarret Mizo, Shaun Ramento
 * 
 */
public class ListPowerTimeStamp extends UserCommandInterface implements UserCommands {

  @Override
  public String doCommand(String args) {
    String[] inputString = args.split(" ");
    String output = null;
    try {
      output = listPowerTimeStamp(inputString[1], inputString[2], inputString[4]);
    }
    catch (WattDepotClientException e) {
      output = "Power Time Stamp error\n";
    }
    return output;
  }

  /**
   * Prints the power generated (or consumed) by the source at the given timestamp. The power value
   * is interpolated if there is no corresponding sensor data instance.
   * 
   * @param power generated or consumed
   * @param sourceName Name of one of the public sources is the system.
   * @param timestamp A timestamp inputed by user.
   * @throws WattDepotClientException Throws exception.
   * @return String of power generated or consumed.
   */
  public String listPowerTimeStamp(String power, String sourceName, String timestamp)
      throws WattDepotClientException {
    // String that will be returned
    StringBuffer buffer = new StringBuffer();
    ValidateDay day = new ValidateDay();
    String newLine = "\n";
    if (!sourceExists(sourceName)) {
      // return to command prompt
      return "Source does not exist\n";
    }

    if (sourceExists(sourceName)) {
      // validates the timestamp into XMLGregorianCalendar
      XMLGregorianCalendar input = day.validateDay(timestamp);

      if (power.equalsIgnoreCase(GENERATED)) {
        // System.out.println("Timestamp = " + input);
        // System.out.println(getClient().getPowerGenerated(sourceName, input));
        buffer.append(getClient().getPowerGenerated(sourceName, input));
        buffer.append(newLine);
      }
      else if (power.equalsIgnoreCase(CONSUMED)) {
        // System.out.println("Timestamp = " + input);
        // System.out.println(getClient().getPowerConsumed(sourceName, input));
        buffer.append(getClient().getPowerConsumed(sourceName, input));
        buffer.append(newLine);
      }
    }

    return buffer.toString();
  }
}
